package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class QuanZiService {

    @Reference
    private QuanZiApi quanZiApi;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;
    @Reference
    private VisitorsApi visitorsApi;
    //获取好友圈子表
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        PageResult pageResult= new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //获取user对象
        User user = UserThreadLocal.get();
        if (null==user){
            return pageResult;
        }
        //获取发布集合
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> publishList = pageInfo.getRecords();
        if (CollUtil.isEmpty(publishList)){
            return pageResult;//为空查不到 该ID好友集合对应的发布信息
        }
        //填充publish---quanzi
        List<QuanZiVo>  quanzivoList = new ArrayList<>();
        this.fillPublishToQuanZiVo(quanzivoList,publishList);//填充publish信息到quanzi中
        //收集所有用户的id
        List<Object> users = CollUtil.getFieldValues(publishList, "userId");
        //填充userInfo---quanzi
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(users);
        for (QuanZiVo quanZiVo : quanzivoList) {
            for (UserInfo userInfo : userInfos) {
                if (quanZiVo.getUserId().longValue()==userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo,quanZiVo);
                    break;
                }
            }
        }
       pageResult.setItems(quanzivoList);
        return pageResult;
    }
    //发布动态
    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        //获取user
        User user = UserThreadLocal.get();
        Publish publish = new Publish();
        publish.setUserId(user.getId());//用户id
        publish.setText(textContent);//发布文字
        //照片视频
        publish.setLongitude(longitude);//纬度
        publish.setLatitude(latitude);//经度
        publish.setLocationName("黑马洗浴中心");
        publish.setSeeType(1);//发布私密度

        //上传图片视频，
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult upload = this.picUploadService.upload(file);
            picUrls.add(upload.getName());

        }
        publish.setMedias(picUrls);//填充路径

        return this.quanZiApi.savePublish(publish);

    }

    //获取圈子推荐动态列表
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //获取user
        User user = UserThreadLocal.get();
        //通过dubbo查询publish集合

        //获取发布集合
        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> publishList = pageInfo.getRecords();
        if (CollUtil.isEmpty(publishList)){
            return pageResult;//为空查不到 该ID好友集合对应的发布信息
        }
        //填充publish---quanzi
        List<QuanZiVo>  quanzivoList = new ArrayList<>();
        fillPublishToQuanZiVo(quanzivoList,publishList);//填充publish信息到quanzi中
        //收集所有用户的id
        List<Object> users = CollUtil.getFieldValues(publishList, "userId");
        //填充userInfo---quanzi
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(users);
        for (QuanZiVo quanZiVo : quanzivoList) {
            for (UserInfo userInfo : userInfos) {
                if (quanZiVo.getUserId().longValue()==userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo,quanZiVo);
                    break;
                }
            }
        }
        pageResult.setItems(quanzivoList);
        return pageResult;
    }
    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        User user = UserThreadLocal.get();
        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //点赞数        quanZiVo.setHasLoved(0); //
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //喜欢数
    }

    /**
     * 填充publish信息
     * @param
     * @param
     * @return
     */
    //填充信息到圈子结果集合中
    private void fillPublishToQuanZiVo(List<QuanZiVo> quanzivoList,List<Publish> publishList){
        for (Publish publish : publishList) {
            QuanZiVo quanzivo = new QuanZiVo();
            quanzivo.setId(publish.getId().toHexString());//发布表的主键发布id
            quanzivo.setTextContent(publish.getText());//文本
            quanzivo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanzivo.setUserId(publish.getUserId());//好友ID
            quanzivo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanzivoList.add(quanzivo);
        }
    }

    public Long likeComment(String publishId) {
        //获取用户
        User user = UserThreadLocal.get();
        //点赞
        Boolean result = this.quanZiApi.likeComment(user.getId(), publishId);
        if (result){
            //点赞成功获取当前点赞数量
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }
    //删除点赞
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if (result){
            //获取删除后的数量
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        //喜欢
        Boolean result = this.quanZiApi.loveComment(user.getId(), publishId);
        if(result){
            //查询喜欢数
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }
    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }

    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        //取消喜欢
        Boolean result = this.quanZiApi.disLoveComment(user.getId(), publishId);
        if(result){
            //查询喜欢数
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }
    //查询单个动态
    public QuanZiVo queryById(String publishId){
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish==null){
            return null;
        }
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        List<Publish> publishList = new ArrayList<>();
        publishList.add(publish);
        this.fillPublishToQuanZiVo(quanZiVoList,publishList);
        this.fillUserInfoToQuanZiVo(userInfoService.queryById(publish.getUserId()),quanZiVoList.get(0));
        QuanZiVo quanZiVo = quanZiVoList.get(0);
        return quanZiVo;
    }
    /**
     * 查询评论列表
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //查询评论表
        PageInfo<Comment> commentList = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = commentList.getRecords();
        if (CollUtil.isEmpty(records)){
            return pageResult;//当前没有评论
        }
        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(userIds);
        List<CommentVo> result = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));


            for (UserInfo userInfo : userInfos) {
                if(ObjectUtil.equals(record.getUserId(), userInfo.getUserId())){

                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            result.add(commentVo);
        }
        pageResult.setItems(result);
        return pageResult;
    }
    //发表评论
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
       return this.quanZiApi.saveComment(user.getId(),publishId,content);
    }
    //查询用户相册表
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //查该ID相册表
       PageInfo<Publish> publishPageInfo= this.quanZiApi.queryAlbumList(userId,page,pageSize);
        List<Publish> records = publishPageInfo.getRecords();
        if (CollUtil.isEmpty(records)){
           return pageResult;
       }
       //填充数据
        List<QuanZiVo> quanZiVoList = this.fillQuanZiVo(records);
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }
    //谁看过我列表
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        //获取看过我的id集合
        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userIds);
        //填充
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }
}
